package com.sap.sap_mangers.controller;

import com.sap.sap_mangers.Vo.SawbsVo.SawbsMessageVo;
import com.sap.sap_mangers.Vo.UserVo.UserMessage;
import com.sap.sap_mangers.dto.user.NoticeDto;
import com.sap.sap_mangers.dto.user.SoftAssociationChange;
import com.sap.sap_mangers.pojo.*;
import com.sap.sap_mangers.service.CacheService;
import com.sap.sap_mangers.service.SawbsService;
import com.sap.sap_mangers.service.UserService;
import com.sap.sap_mangers.until.ConstantUntil;
import com.sap.sap_mangers.until.CosUntil;
import com.sap.sap_mangers.until.JwtUtil;
import com.sap.sap_mangers.until.SimpleJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 樊东升
 * @date 2022/7/24 11:53
 */
@RestController
@RequestMapping("/User")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private SawbsService sawbsService;
    @Autowired
    private CacheService cacheService;

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getUserSessionList")
    public SimpleJson getUserSessionList(Integer session) {
        return new SimpleJson(0, "获取成功", userService.getUserSessionList(session));
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getUserMessage")
    public SimpleJson getUserMessage() {
        UserMessage userMessage = userService.getUserMessage(null);
        SapSawbsMangers sapSawbsMangers = sawbsService.getSapSawbsMangers(JwtUtil.getUserForToken());
        if (sapSawbsMangers == null) {
            userMessage.setManager(0);
        } else {
            if (sapSawbsMangers.getSawbsMangersExist() == 1) {
                userMessage.setManager(2);
            } else {
                userMessage.setManager(1);
            }
        }
        return new SimpleJson(0, "信息获取成功", userMessage);
    }

    @PreAuthorize("hasAuthority('游客')")
    @PutMapping("/updateUserDetails")
    public SimpleJson updateUserDetails(@RequestBody DetailsUser detailsUser) {
        detailsUser.setUserDetailsId(JwtUtil.getUserForToken());
        return userService.updateUserDefinition(detailsUser);
    }

    @PutMapping("/updatePassword")
    public SimpleJson updatePassword(@RequestBody User user) {
        if (user.getCode() == null || user.getCode().length() != ConstantUntil.PASSWORD_CODE_LENGTH) {
            return new SimpleJson(1, "验证码为空或者格式不正确");
        }
        if (user.getUsername() != null || user.getUsername().length() != 0) {
            UserMessage userMessage = userService.getUserMessage(user.getUsername());
            if (userMessage == null) {
                return new SimpleJson(1, "用户不存在");
            }
        } else {
            return new SimpleJson(1, "用户名为空");
        }
        if (user.getPassword().length() == 0 || user.getPassword() == null) {
            return new SimpleJson(1, "密码为空");
        }
        cacheService.deleteCacheUserToRedis(user.getUsername());
        return userService.identityUsernameAndQq(user);
    }

    @PostMapping("/generateCode")
    public SimpleJson generateCode(@RequestBody User user) {
        try {
            return userService.generateCode(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(1, "失败！");
        }
    }

    /**
     * 当没有QQ号时添加QQ号(21级的账号在注册时没有qq号，之后的不存在这种情况)
     *
     * @param user 用户
     * @return 视图
     */
    @PostMapping("/addQQ")
    public SimpleJson addQq(@RequestBody User user) {
        return userService.addQq(user.getQq(), user.getUsername());
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getAllMangerCorrespondenceDefaultByDynamicTable")
    public SimpleJson getAllMangerCorrespondenceDefaultByDynamicTable(DynamicMessage dynamicMessage) {
        List<ManagerCorrespondence> managerCorrespondenceList = sawbsService.getAllManagerCorrespondenceDefaultByDynamicTable(dynamicMessage);
        if (managerCorrespondenceList == null || managerCorrespondenceList.size() == 0) {
            return new SimpleJson(1, "获取失败，当前无负责人");
        }
        return new SimpleJson(0, "对应信息获取成功", managerCorrespondenceList);
    }


    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getManagerInformationOfUser")
    public SimpleJson getManagerInformationOfUser() {
        String mangerId = sawbsService.getMangerId();
        if (mangerId == null) {
            return new SimpleJson(1, "您当前没有负责人");
        }
        UserMessage userMessage = userService.getUserMessage(mangerId);
        return new SimpleJson(0, "您的负责人信息获取成功", userMessage);
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getHeadShot")
    public SimpleJson getHeadShot() {
        return userService.getUserHeadShot(JwtUtil.getUserForToken());
    }

    @PreAuthorize("hasAuthority('游客')")
    @PostMapping("/updateHeadShot")
    public SimpleJson updateHeadShot(@RequestParam(value = "file") MultipartFile multipartFile) {
        String imgName;
        if (multipartFile != null && !multipartFile.isEmpty()) {

            try {
                //获取图片名称
                imgName = multipartFile.getOriginalFilename();
                int index = imgName != null ? imgName.lastIndexOf(".jpg") : 0;
                int length = imgName != null ? imgName.length() : 0;
                int jpgIndex = length - index;
                if (jpgIndex != 4) {
                    if (imgName != null) {
                        index = imgName.lastIndexOf(".png");
                    }
                    int pngIndex = length - index;
                    if (pngIndex != 4) {
                        return new SimpleJson(3, "图片格式错误,仅支持JPG/PNG");
                    }
                }
            } catch (Exception e) {
                return new SimpleJson(1, "文件上传失败！");
            }
            return userService.updateHeadShot(multipartFile);
        } else {
            return new SimpleJson(2, "文件为null，上传失败！");
        }
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @PostMapping("/updateHeadPortrait")
    public SimpleJson updateHeadPortrait(@RequestParam(value = "file") MultipartFile multipartFile) {
        return SimpleJson.SUCCESS;
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/getUserWeekScore")
    public SimpleJson getUserScore(@RequestBody SawbsMessageVo sawbsMessageVo) {
        return sawbsService.getWeekScore(sawbsMessageVo);
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getUsersActivityMessageOfYear")
    public SimpleJson getUsersActivityMessageOfYear(Integer year) {
        return sawbsService.getUsersActivityMessageOfYear(year);
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/Notice/getNoticeByUsername")
    public SimpleJson getNoticeByUsername() {
        return userService.getNoticeByUsername();
    }

    @PreAuthorize("hasAuthority('旧管理员')")
    @GetMapping("/Notice/getNoticeMessage")
    public SimpleJson getNoticeMessage() {
        return userService.getNoticeMessage();
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/Notice/confirmationMessage")
    public SimpleJson confirmationMessage(@RequestParam("noticeId") String noticeId) {
        return userService.confirmationMessage(noticeId);
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/Notice/confirmationMessageList")
    public SimpleJson confirmationMessageList() {
        try {
            SimpleJson noticeMessage = userService.getNoticeByUsername();
            List<SapUserNotice> data = (List<SapUserNotice>) noticeMessage.getData();
            for (SapUserNotice datum : data) {
                userService.confirmationMessage(String.valueOf(datum.getUserNoticeId()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return SimpleJson.FAILURE;
        }
        return SimpleJson.SUCCESS;
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @PostMapping("/Notice/sendNotice")
    public SimpleJson sendNotice(@RequestBody NoticeDto noticeDto) {
        return userService.sendNotice(noticeDto);
    }

    @PreAuthorize("hasAuthority('正式成员')")
    @GetMapping("/confirmToken")
    public SimpleJson confirmToken() {
        return SimpleJson.SUCCESS;
    }

    /**
     * 软协换届
     *
     * @return 视图
     */
    @PreAuthorize("hasAuthority('会长')")
    @PostMapping("/softAssociationChange")
    public SimpleJson softAssociationChange(@RequestBody SoftAssociationChange softAssociationChange) {
        try {
            return userService.softAssociationChange(softAssociationChange);
        } catch (Exception e) {
            e.printStackTrace();
            return SimpleJson.FAILURE;
        }
    }

    /**
     * 很重要的接口，可以手动赋予人员权限以及身份(谨慎操作)
     *
     * @return 视图
     */
    @PreAuthorize("hasAuthority('会长')")
    @GetMapping("/addPosts")
    public SimpleJson addPosts(@RequestParam("username") String username, @RequestParam("rank") Integer rank) {
        UserMessage userMessage = userService.getUserMessage(username);
        if (userMessage == null) {
            return new SimpleJson(1, "账号不存在");
        }
        int role = -1;
        if (rank == 1) {
            role = 1;
        } else if (rank <= 9) {
            role = 2;
        } else if (rank == 10) {
            role = 3;
        } else if (rank == 11) {
            role = 4;
        } else if (rank == 12) {
            role = 5;
        } else {
            return new SimpleJson(1, "参数错误");
        }
        userService.updateRolePosts(username, role, rank);
        return SimpleJson.SUCCESS;
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getMinister")
    public SimpleJson getMinister() {
        List<Minister> minister = userService.getMinister();
        for (Minister minister1 : minister) {
            minister1.setName(minister1.getName() + "(" + minister1.getUsername() + ")");
        }
        minister.removeIf(user -> user.getRole() <= 3);
        return new SimpleJson(minister);
    }


    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getOrdinaryMembers")
    public SimpleJson getOrdinaryMembers() {
        List<Minister> ordinaryMembers = userService.getOrdinaryMembers();
        List<Minister> jsonBack = new ArrayList<>();
        for (Minister ordinaryMember : ordinaryMembers) {
            if (ordinaryMember.getRole() <=9 && ordinaryMember.getRole() > 3) {
                ordinaryMember.setName(ordinaryMember.getName() + "(" + ordinaryMember.getUsername() + ")");
                jsonBack.add(ordinaryMember);
            } else if (ordinaryMember.getRole() == 11) {
                ordinaryMember.setName(ordinaryMember.getName() + "(" + ordinaryMember.getUsername() + ")");
                jsonBack.add(ordinaryMember);
            }
        }
        return new SimpleJson(jsonBack);
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getSapPeopleNumberInfo")
    public SimpleJson getSapPeopleNumberInfo() {
        return userService.getSapPeopleNumberInfo();
    }

    @PreAuthorize("hasAuthority('游客')")
    @PostMapping("/handleAdviceOrQuestion")
    public SimpleJson handleAdviceOrQuestion(@RequestParam("title") String title,
                                             @RequestParam("type") Integer type,
                                             @RequestParam("describe") String describe,
                                             @RequestParam(value = "img", required = false) MultipartFile img) {
        //信息校验
        if(!StringUtils.hasText(title)||!StringUtils.hasText(describe)||(type!=0&&type!=1)){
            return new SimpleJson(1,"提交失败：请勿提交无效内容");
        }
        if(title.length()>64){
            return new SimpleJson(1,"标题字数不得超过64");
        }
        if(describe.length()>1024){
            return new SimpleJson(1,"问题描述不得超过1024");
        }
        String imgName = "";
        if (img != null) {
            //获取图片名称
            imgName = img.getOriginalFilename();
            int index = imgName != null ? imgName.lastIndexOf(".jpg") : 0;
            int length = imgName != null ? imgName.length() : 0;
            int jpgIndex = length - index;
            if (jpgIndex != 4) {
                if (imgName != null) {
                    index = imgName.lastIndexOf(".png");
                }
                int pngIndex = length - index;
                if (pngIndex != 4) {
                    return new SimpleJson(3, "图片格式错误,仅支持JPG/PNG");
                }
            }
        }
        //信息填充
        SapAdviceOrQuestion sapAdviceOrQuestion = new SapAdviceOrQuestion();
        sapAdviceOrQuestion.setUsername(JwtUtil.getUserForToken());
        sapAdviceOrQuestion.setTitle(title);
        sapAdviceOrQuestion.setDescribe(describe);
        sapAdviceOrQuestion.setType(type);
        sapAdviceOrQuestion.setTime(new Date());
        CosUntil cosUntil = new CosUntil();
        String url = "SapAdviceOrQuestion" + System.currentTimeMillis() + "_"+sapAdviceOrQuestion.getUsername()+imgName;
        try {
            if(img!=null && !img.isEmpty()) {
                sapAdviceOrQuestion.setImgPath(cosUntil.getCosUrl(img, url));
            }
            userService.addAdviceOrQuestion(sapAdviceOrQuestion);
            return userService.sendAdviceOrQuestionOfNotice(sapAdviceOrQuestion);
        } catch (Exception e) {
            return new SimpleJson(5,"系统异常错误："+e.getMessage());
        }
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getSessionYear")
    public SimpleJson getSessionYear(){
        return new SimpleJson(0,"获取成功",userService.getSessionYear());
    }
}
